﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.CallRoute;

public partial class CallRoute_Off_Day_Maintain : PageBase, ICallbackEventHandler
{
    
    private string _OrgId = string.Empty;
    private static DataTable _OrgTable = null;//部门列表
    private static StringBuilder _MobileUserStrB = null;//业代列表
    private static StringBuilder _MobileUserHolidayStrB = null;//业代假日列表
    private static int _Result = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        //Register Client Script Block
        string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ShowHoliday", "context");
        string cbScript = "function UseCallBack(arg,context){" + cbReference + ";}";

        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cbScript, true);

        if (!IsPostBack)
        {
            //初始化假日 
            DataTable dt = new RouteManager().GetHoliday();
            SetHoliday(dt);
            //
            BindTree();
        }
    }
    /// <summary>
    /// 将假日存放到隐藏控件,用于客户端的解析显示
    /// </summary>
    /// <param name="dt"></param>
    private void SetHoliday(DataTable dt)
    {
        StringBuilder dateValues = new StringBuilder();
        foreach (DataRow row in dt.Rows)
        {
            dateValues.Append(((DateTime)row["Date"]).ToShortDateString() + ",");
        }
        txtholiday.Value = dateValues.ToString().TrimEnd(',');
    }

    /// <summary>
    /// 更改选择节点为展开或者收缩形式
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void TreeOrg_SelectedNodeChanged(object sender, EventArgs e)
    {
        if (TreeOrg.SelectedNode.Expanded == true)
            TreeOrg.SelectedNode.Collapse();
        else
            TreeOrg.SelectedNode.Expand();

        if (TreeOrg2.SelectedNode.Expanded == true)
            TreeOrg2.SelectedNode.Collapse();
        else
            TreeOrg2.SelectedNode.Expand();
    }

    /// <summary>
    /// 
    /// </summary>
    private void BindTree()
    {
        TreeOrg.Nodes.Clear();
        TreeOrg2.Nodes.Clear();
        _OrgTable = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, "and ACTIVE=1");
        DataRow[] rows = _OrgTable.Select("level=1");
        foreach (DataRow row in rows)
        {
            TreeNode node = new TreeNode();
            node.Text = row["name"].ToString();
            node.Value = row["id"].ToString();
            node.SelectAction = TreeNodeSelectAction.Expand;
            node.ShowCheckBox = true;
            node.Checked = row["OffDay_OrgId"].ToString() != "";
            TreeOrg.Attributes.Add("onClick", "client_OnTreeNodeChecked()");

            AddSubNode(node, _OrgTable, node.Checked.ToString());
            TreeOrg.Nodes.Add(node);

            TreeNode node2 = new TreeNode();
            node2.Text = row["name"].ToString();
            node2.Value = row["id"].ToString();
            node2.SelectAction = TreeNodeSelectAction.Expand;
            node2.ShowCheckBox = true;
            TreeOrg2.Attributes.Add("onClick", "SingleCheck()");

            AddSubNode(node2, _OrgTable, null);
            TreeOrg2.Nodes.Add(node2);
        }
        TreeOrg2.CollapseAll();

    }

    /// <summary>
    /// 添加子节点
    /// </summary>
    /// <param name="node"></param>
    /// <param name="dt"></param>
    private void AddSubNode(TreeNode node, DataTable dt, string check)
    {
        DataRow[] rows = dt.Select("parentid=" + node.Value);
        foreach (DataRow row in rows)
        {
            TreeNode ChildNode = new TreeNode();
            ChildNode.Text = row["name"].ToString();
            ChildNode.Value = row["id"].ToString();
            ChildNode.SelectAction = TreeNodeSelectAction.Expand;
            ChildNode.ShowCheckBox = true;
            if (check != null)
                ChildNode.Checked = row["OffDay_OrgId"].ToString() != "" || check == "True";
            AddSubNode(ChildNode, dt, ChildNode.Checked.ToString());
            node.ChildNodes.Add(ChildNode);
        }
    }

    private string GetSelectedOrgIDs(string SelectedOrgName)
    {
        StringBuilder values = new StringBuilder();

        //通过
        DataRow[] rows = _OrgTable.Select("name in (" + SelectedOrgName + ")");
        foreach (DataRow row in rows)
        {
            values.Append(row["id"].ToString() + ",");
        }
        return values.ToString().TrimEnd(',');
    }

    #region ICallbackEventHandler Members

    public string GetCallbackResult()
    {
        int r = _Result;
        _Result = 0;
        if (r >= 0)
        {
            return r.ToString();
        }
        else if (r == -1)
        {
            return _MobileUserStrB.ToString().TrimEnd('$');
        }
        else if (r == -2)
        {
            return "SMUH$" + _MobileUserHolidayStrB.ToString().TrimEnd(',');
        }
        return "0";
    }

    public void RaiseCallbackEvent(string eventArgument)
    {
        try
        {
            //获取业代,填充业代下拉列表
            if (eventArgument.StartsWith("U"))
            {
                eventArgument = eventArgument.TrimStart('U');
                DataTable dt = new UserManager().GetUserTableByOrgName(eventArgument, MyStateManager.DomainID);
                _MobileUserStrB = new StringBuilder();

                foreach (DataRow row in dt.Rows) //遍历所有业代返回给客户端
                {
                    _MobileUserStrB.Append(row["UserId"].ToString() + ",");
                    _MobileUserStrB.Append(row["PersonName"].ToString() + "$");
                }
                _Result = -1;
            }
            else if (eventArgument.StartsWith("M")) //获取业代假日
            {
                eventArgument = eventArgument.TrimStart('M');
                if (eventArgument != "")
                {
                    _MobileUserHolidayStrB = new StringBuilder();

                    DataTable dt = new RouteManager().GetMobileUserHoliday(int.Parse(eventArgument));
                    foreach (DataRow row in dt.Rows)
                    {
                        _MobileUserHolidayStrB.Append(((DateTime)row["Date"]).ToShortDateString() + ",");
                    }
                    _Result = -2;
                }
            }
            else//保存假日
            {
                RouteManager routManager = new RouteManager();
                string[] args = eventArgument.Split('&');

                if (args[1].EndsWith("O"))//如果保存组织假日
                {
                    string orgId = GetSelectedOrgIDs(args[1].TrimEnd('O').TrimEnd(','));//获取部门ID                   

                    //保存到数据库
                    _Result = routManager.SaveHoliday(orgId, args[0].TrimEnd(','));
                }
                else if (args[1].EndsWith("P"))//如果保存个人假日
                {
                    int userID;
                    int.TryParse(args[1].TrimEnd('P'), out userID);
                    //保存到数据库
                    _Result = routManager.SaveHoliday(userID, args[0].TrimEnd(','));
                }
                _Result = 2;
            }
        }
        catch { }
    }

    #endregion
}
